<?php
	header('Content-type: application/json;charset=utf-8');
 	//初始化mysqli对象
	$mysqli = new mysqli('localhost','root','root','user');

	//判断数据库是否连接成功
	if($mysqli-> connect_errno){
		echo json_encode('{"result":-1,"status":"连接数据库失败"}');
	    die($mysqli->connect_error);
	}

	//设置字符集
	$mysqli->set_charset("utf8");

	$type = isset($_GET["type"]) ? $_GET["type"]: "";
	
	if($type=="add"){//添加操作
		$username = $_GET["username"];
		$password = $_GET["password"];
		/*$username = $_POST["username"];
		$password = $_POST["password"];*/
		// $postData = file_get_contents('php://input', true);  
		// $obj=json_decode($postData); 
		// echo $GLOBALS['HTTP_RAW_POST_DATA'];
		if($username!="" || $password!=""){
				//sql 语句
				$sql = "insert into user(`username`, `password`) value('".$username."','".$password."')";
			 	$res = $mysqli->query($sql);
			 	if ($res==true && $mysqli -> affected_rows) {
			 		echo '{"result":1,"status":"成功"}';
			 	}else{
			 		echo '{"result":0,"status":"添加失败"}';
			 	}
		}
	}
	if($type==""){//不传值默认表示查询所有
		$sql = "select * from user";
		$res = $mysqli->query($sql);
		// echo $res->num_rows;
		$tpl_db_rows = array();
	 	if ($res->num_rows > 0) {
		    // 输出每行数据
		    while($row = $res->fetch_assoc()) {
		    		$tpl_db_rows[] = $row;
			}
		}
		echo json_encode($tpl_db_rows);
	}
	if($type=="del"){//删除操作
		$id = $_GET["id"];
		//sql 语句
		$sql = "delete from user where id in(".$id.")";
		
		$res = $mysqli->query($sql);
		if ($res==true && $mysqli -> affected_rows) {
			echo '{"result":1,"status":"成功"}';
		}else{
			echo '{"result":0,"status":"删除失败"}';
		}
	}else if ($type == "get"){//获取单条信息
		$id = $_GET["id"];
		//sql 语句
		$sql = "select * from user where id=".$id;
		//结果集
		$res = $mysqli->query($sql);
	 	$tpl_db_rows = array();
	 	if ($res->num_rows > 0) {
		    // 输出每行数据
		    while($row = $res->fetch_assoc()) {
		    	$tpl_db_rows[] = $row;
			}
		}
		echo json_encode($tpl_db_rows);		
	}else if ($type == "update"){//更新操作
		$id = $_GET["id"];
		$username = $_GET["username"];
		$password = $_GET["password"];
		//sql 语句
		$sql = "update user set username='".$username."',password='".$password."' where id=".$id;
		//状态
	 	$res = $mysqli-> query($sql);
		if ($res==true && $mysqli -> affected_rows) {
			echo '{"result":1,"status":"成功"}';
		}else{
			echo '{"result":0,"status":"更新失败"}';
		}
	}

	$mysqli->close();
 ?>